#include "log.h"

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>

using std::cerr;
using std::endl;
using std::setw;
using std::setfill;

Log::Log(LogType type, const char* file_name, int line_no) {
	type_ = type;

	if (type == INVISIBLE)
		return;

	time_t clock = time(NULL);
	tm* timeofday = localtime(&clock);

	switch (type_) {
		case INVISIBLE: break; // stupid warning
		case DEBUG: cerr << "D"; break;
		case INFO: cerr << "I"; break;
		case WARN: cerr << "W"; break;
		case FATAL: cerr << "F"; break;
	}

	cerr << setw(2) << setfill('0') << timeofday->tm_hour;
	cerr << setw(2) << setfill('0') << timeofday->tm_min;
	cerr << setw(2) << setfill('0') << timeofday->tm_sec << " ";
	cerr << file_name << ":" << line_no << " : ";
}

Log::~Log() {
#ifdef NDEBUG
	if (type() != INVISIBLE && type() != DEBUG)
#else
	if (type() != INVISIBLE)
#endif
			cerr << endl;

	if (type() == FATAL)
		exit(EXIT_FAILURE);
}

Log assert(bool assertion, const char* file_name, int line_no) {
	if (assertion)
		return Log(INVISIBLE, file_name, line_no);
	return Log(FATAL, file_name, line_no);
}
